package 事务操作;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Transaction {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/db_jdbc_demo" +
                "?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "xiaotong123";
        Connection conn = null;
        Statement stmt = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            DriverManager.getConnection(url, user, pass);
            String sql1 = "update t _account set money = money -5000 where id = '1'";
            String sql2 = "update t _account set money = money +5000 where id = '2'";
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            int i = stmt.executeUpdate(sql1);
//            int x = 5 / 0;
            int j = stmt.executeUpdate(sql2);
            if (i + j == 2) {
                System.out.println("转账成功！");
                conn.commit();
            } else {
                System.out.println("转账失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转账出现异常");
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
                try {
                    stmt.close();
                    conn.commit();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}


